package com.summer.data.rs.map;

import com.summer.data.dialect.Dialect;
import com.summer.data.exception.BaseException;
import com.summer.data.table.BaseColumn;
import com.summer.data.table.BaseTable;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 345480567@qq.com
 */

public class ResultSetToTableFun<T extends BaseTable> extends AbstractResultSetMapFun<T> {

    Class<T> clazz;

    public ResultSetToTableFun(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T map(ResultSet resultSet, Dialect dialect) throws BaseException {
        try {
            T t = clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();
            for (int i=0; i<fields.length; i++) {
                Field field = fields[i];
                Object attr = field.get(t);
                if (attr instanceof BaseColumn) {
                    BaseColumn column = (BaseColumn)attr;
                    Integer colPos = getColumnIndex(resultSet, column.colName, dialect);
                    column.fetchNotNullValue(resultSet, colPos);
                }
            }

            return t;
        } catch (InstantiationException e) {
            throw new BaseException(e);
        } catch (IllegalAccessException e) {
            throw new BaseException(e);
        } catch (SQLException e) {
            throw new BaseException(e);
        }
    }
}

